<template>
  <div class="h-full px-4 py-3 rounded-lg">
    <div class="flex justify-end">
      <div class="flex">
        <a-input
          v-model:value.trim="searchForm.defectResult"
          placeholder="请输入缺陷结果"
          v-filter-special-chars
          class="_input"
        />
        <a-select
          class="_input"
          v-model:value="searchForm.deviceName"
          allow-clear
          placeholder="选择设备名称"
          :options="statusList"
        />
        <a-range-picker
          class="_input"
          :value="hackDatesValue || dateRange"
          :separator="'至'"
          format="YYYY-MM-DD"
          @calendarChange="onCalendarChange"
          @openChange="onOpenChange"
          @change="onRangeChange"
          :disabledDate="disabledDate"
        />
        <SerchButtom @search="getList(true, true)" @reset="reset" />
      </div>
    </div>

    <div class="mt-3 h-[calc(100%-6rem)] overflow-y-auto">
      <div class="mt-[10rem]" v-if="!dataSource?.length">
        <no-data />
      </div>
      <a-spin tip="正在加载..." :spinning="loading" v-else>
        <div class="grid">
          <div
            class="rounded-[0.5rem] border border-[#E5E6EB]"
            v-for="item in dataSource"
            :key="item.deviceId"
            @click="openModal(item)"
          >
            <div class="flex justify-between leading-[2.75rem] px-4">
              <span class="text-[#000] font-[600]">{{ item.deviceName }}</span>
              <!-- <span
                class="text-[#00796A] font-[600] cursor-pointer"
                @click="openModal(item)"
              >
                缺陷详情
              </span> -->
            </div>
            <img class="max-h-[160px] m-auto" :src="item.thumbnailImagePath" />
            <div class="flex px-4 mt-[12px]">
              <div class="w-[4.375rem] text-[#4E5969]">检测时间:</div>
              <span class="text-[#1D2129]">{{ item.algTime }}</span>
            </div>
            <div class="flex px-4 mt-[6px]">
              <div class="w-[4.375rem] text-[#4E5969]">缺陷结果:</div>
              <span class="w-[260px] leading-[18px] text-[#1D2129] pb-4">
                {{ item.defectResult }}
              </span>
            </div>
          </div>
        </div>
      </a-spin>
    </div>
    <div class="mt-3 h-8">
      <Pagination @getListByPage="getListByPage" ref="paginationRef" />
    </div>
  </div>

  <IndexModal ref="indexModalRef" @isOk="getList(true, true)" />
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import dayjs, { Dayjs } from 'dayjs'

import IndexModal from './IndexModal.vue'
import SerchButtom from '@/components/YuanQi-SearchButtom.vue'

import { list, getDevList } from './serve.api'

const dataSource = ref()
const loading = ref<boolean>(false)
const paginationRef = ref()

const statusList = ref<any[]>([])

const indexModalRef = ref()

const dateRange = ref<Dayjs[]>([dayjs().subtract(1, 'month'), dayjs()])
const dates = ref<Dayjs[]>([])
const hackDatesValue = ref<Dayjs[]>()

let searchFormClone = {
  pageNum: 1,
  pageSize: 10,
  algTimeBegin: '',
  algTimeEnd: '',
  deviceName: undefined,
  defectResult: ''
}

// 搜索参数
const searchForm = reactive({
  deviceName: undefined,
  defectResult: ''
})

const disabledDate = (current: Dayjs) => {
  const currentFormat = dayjs(current).format('YYYY-MM-DD HH:mm:ss')
  const currentDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
  if (currentDate < currentFormat) return true
  if (!dates.value || (!dates.value[0] && !dates.value[1])) {
    return false
  }
  if (dates.value[0] && current > dayjs(dates.value[0]).add(1, 'year'))
    return true
  if (dates.value[1] && current < dayjs(dates.value[1]).subtract(1, 'year'))
    return true
  return false
}

const onOpenChange = (open: boolean) => {
  if (open) {
    dates.value = [] as any
    hackDatesValue.value = [] as any
  } else {
    hackDatesValue.value = undefined
  }
}
const onCalendarChange = (val: Dayjs[]) => {
  dates.value = val
}
const onRangeChange = (val: Dayjs[]) => {
  dateRange.value = val
}

// 重置
const reset = () => {
  searchForm.defectResult = ''
  searchForm.deviceName = undefined
  dateRange.value = [dayjs().subtract(1, 'month'), dayjs()]
  getList(true, true)
}

const openModal = async (data?: any) => {
  indexModalRef.value.showModal(data)
}

const pagination = reactive({
  total: 0,
  pageSize: 10, // 每页中显示10条数据
  position: ['bottomCenter'],
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`
})

// 日期选择处理
const setTime = () => {
  if (dateRange.value?.length) {
    return {
      startDate: dayjs(dateRange.value[0]).format('YYYY-MM-DD 00:00:00'),
      endDate: dayjs(dateRange.value[1]).format('YYYY-MM-DD 23:59:59')
    }
  } else {
    return {
      startDate: '',
      endDate: ''
    }
  }
}

// 初始化数据
const getList = (flag = false, isSearch = false) => {
  if (flag) {
    pagination.current = 1
    paginationRef.value.changeCurrent(pagination.current)
  }
  loading.value = true
  dataSource.value = []
  const { startDate, endDate } = setTime()
  const params = {
    defectResult: searchForm.defectResult,
    deviceName: searchForm.deviceName,
    algTimeBegin: startDate,
    algTimeEnd: endDate,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  }
  if (isSearch) {
    searchFormClone = JSON.parse(JSON.stringify(params))
  } else {
    params.deviceName = searchFormClone.deviceName
    params.defectResult = searchFormClone.defectResult
    params.algTimeBegin = searchFormClone.algTimeBegin
    params.algTimeEnd = searchFormClone.algTimeEnd
  }

  list(params)
    .then((res) => {
      if (res) {
        console.log(res, '缺陷管理列表')

        dataSource.value = res.list
        pagination.total = res.total

        paginationRef.value.changeTotal(pagination.total)
        loading.value = false
      } else {
        loading.value = false
      }
    })
    .catch(() => {
      loading.value = false
    })
}

const getListByPage = (page: number, pageSize: number) => {
  if (pagination.current !== page) {
    pagination.current = page
    getList()
  }
  if (pagination.pageSize !== pageSize) {
    pagination.pageSize = pageSize
    getList(true)
  }
}

onMounted(() => {
  getDevList().then((res) => {
    statusList.value = res.map((item: any) => ({
      label: item,
      value: item
    }))
  })

  getList(true, true)
})
</script>
<style lang="less" scoped>
._input {
  width: 15.125rem;
  vertical-align: middle;

  &:nth-child(-n + 2) {
    margin-right: 1.25rem;
  }
}

.grid {
  display: grid;
  grid-template-columns: repeat(5, calc((100% - 4rem) / 5));
  grid-gap: 1rem;

  > div:hover {
    cursor: pointer;
    border-color: #00796a;
  }
}
</style>
